package com.eqdd.yiqidian.ui.select;

import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.view.View;

import com.eqdd.yiqidian.R;
import com.eqdd.yiqidian.SelectTextMultiActivityCustom;
import com.eqdd.yiqidian.adapter.recycleadapter.ItemClickSupport;
import com.eqdd.yiqidian.adapter.slimadapter.SlimAdapterEx;
import com.eqdd.yiqidian.adapter.slimadapter.SlimInjector;
import com.eqdd.yiqidian.adapter.slimadapter.viewinjector.IViewInjector;
import com.eqdd.yiqidian.base.BaseActivity;
import com.eqdd.yiqidian.base.Config;
import com.eqdd.yiqidian.bean.rebuild.OptionBean;
import com.eqdd.yiqidian.box.layoutManager.MeasureFlowLayoutManager;
import com.eqdd.yiqidian.http.DialogCallBack;
import com.eqdd.yiqidian.http.HttpConfig;
import com.eqdd.yiqidian.utils.ToastUtil;
import com.eqdd.yiqidian.widget.FlowLayoutManager;
import com.eqdd.yiqidian.widget.NewFlowLayoutManager;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.model.Response;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Flowable;

/**
 * @author吕志豪 .
 * @date 17-12-6  上午9:54.
 * Github :https://github.com/lvzhihao100
 * E-Mail：1030753080@qq.com
 * 简书 :http://www.jianshu.com/u/6e525b929aac
 */

public class SelectTextMultiActivity extends BaseActivity {

    private SelectTextMultiActivityCustom dataBinding;
    private List<TagBean> strings;
    private List<TagBean> results = new ArrayList<>();
    private SlimAdapterEx<TagBean> slimAdapterEx;
    private int deep;
    private int maxNum;
    private int option;

    @Override
    public void initBinding() {
        dataBinding = DataBindingUtil.setContentView(this, R.layout.activity_select_text_multi);
        initTopTitleBar(View.VISIBLE, "选择");
        initTopRightText("确定", v -> {
            if (results.size() > 0) {
                Intent intent = new Intent();
                ArrayList<String> strResults = new ArrayList<>();
                Flowable.fromIterable(results)
                        .subscribe(o -> strResults.add(o.text));
                intent.putStringArrayListExtra(Config.STRING_LIST, strResults);
                setResult(Config.SUCCESS, intent);
                finish();
            } else {
                ToastUtil.showShort("至少选一个");
            }
        });
    }

    @Override
    public void initData() {
        maxNum = getIntent().getIntExtra(Config.MAX_NUM, Integer.MAX_VALUE);
        option = getIntent().getIntExtra(Config.OPTION, 0);
        deep = getIntent().getIntExtra(Config.DEEP, 1);
        loadData();

    }

    private void loadData() {
        OkGo.<List<OptionBean>>get(HttpConfig.BASE_URL + HttpConfig.AREA_OPTIONS)
                .params("type", option)
                .cacheMode(CacheMode.IF_NONE_CACHE_REQUEST)
                .cacheKey(HttpConfig.BASE_URL + HttpConfig.AREA_OPTIONS + option)
                .execute(new DialogCallBack<List<OptionBean>>(SelectTextMultiActivity.this) {
                    @Override
                    public void onSuccess(Response<List<OptionBean>> response) {
                        List<OptionBean> optionBean = response.body();
                        dealData(optionBean);
                    }

                    @Override
                    public void onCacheSuccess(Response<List<OptionBean>> response) {
                        super.onCacheSuccess(response);
                        List<OptionBean> optionBean = response.body();
                        dealData(optionBean);
                    }

                    @Override
                    public void onError(Response<List<OptionBean>> response) {
                        super.onError(response);
                        ToastUtil.showShort("数据获取失败，请稍候重试");
                    }
                });
    }

    private void dealData(List<OptionBean> optionBean) {
        strings = new ArrayList<>();
        switch (deep) {
            case 1://获取一级目录所有条目
                Flowable.fromIterable(optionBean)
                        .subscribe(bean -> strings.add(new TagBean(bean.getName())));
                break;
            case 2://获取二级目录所有条目
                Flowable.fromIterable(optionBean)
                        .flatMap(optionBean12 -> Flowable.fromIterable(optionBean12.getSub()))
                        .subscribe(optionBean1 -> strings.add(new TagBean(optionBean1.getName())));
                break;
            case 3://获取三级目录所有条目
                Flowable.fromIterable(optionBean)
                        .flatMap(optionBean12 -> Flowable.fromIterable(optionBean12.getSub()))
                        .flatMap(optionBean123 -> Flowable.fromIterable(optionBean123.getSub()))
                        .subscribe(optionBean1234 -> strings.add(new TagBean(optionBean1234.getName())), System.out::print);
                break;
        }
        initText();


    }

    private void initText() {
        dataBinding.recyclerView.setLayoutManager(new NewFlowLayoutManager());
        slimAdapterEx = SlimAdapterEx.create().register(R.layout.list_item_95, new SlimInjector<TagBean>() {
            @Override
            public void onInject(TagBean data, IViewInjector injector) {
                injector.text(R.id.bt_tag, data.text)
                        .background(R.id.bt_tag, data.isCheck ?
                                getResources().getDrawable(R.drawable.shape_17_tag_selected) :
                                getResources().getDrawable(R.drawable.shape_17_tag_unselected));
            }
        })/*.register(R.layout.list_item_75, new SlimInjector<Integer>() {
            @Override
            public void onInject(Integer data, IViewInjector injector) {
                injector.with(R.id.autoTextView, view -> {
                    AutoCompleteTextView autoCompleteTextView = (AutoCompleteTextView) view;
                    ArrayAdapter arrayAdapter = new ArrayAdapter(SelectTextMultiActivity.this, R.layout.support_simple_spinner_dropdown_item, strings);
                    //设置适配
                    autoCompleteTextView.setAdapter(arrayAdapter);
                    autoCompleteTextView.setOnItemClickListener((parent, view1, position, id) -> {
                        String tag = (String) parent.getAdapter().getItem(position);
                        slimAdapterEx.getData().add(slimAdapterEx.getData().size() - 1, tag);
                        slimAdapterEx.notifyItemInserted(slimAdapterEx.getData().size() - 2);
                        autoCompleteTextView.setText("");
                        if (slimAdapterEx.getData().size() == maxNum + 1) {
                            slimAdapterEx.getData().remove(maxNum);
                            slimAdapterEx.notifyItemRemoved(maxNum);
                        }
                    });
                    autoCompleteTextView.setThreshold(0);
                });
            }
        }).*/.attachTo(dataBinding.recyclerView).updateData(strings);
        ItemClickSupport.addTo(dataBinding.recyclerView).setOnItemClickListener((recyclerView, position, v) -> {

            slimAdapterEx.getDataItem(position).isCheck = !slimAdapterEx.getDataItem(position).isCheck;
            if (slimAdapterEx.getDataItem(position).isCheck) {
                results.add(slimAdapterEx.getDataItem(position));
            } else {
                results.remove(slimAdapterEx.getDataItem(position));
            }
            if (results.size() == maxNum + 1) {
                ToastUtil.showShort("最多选" + maxNum + "个");
                slimAdapterEx.getDataItem(position).isCheck = !slimAdapterEx.getDataItem(position).isCheck;
                results.remove(slimAdapterEx.getDataItem(position));

            } else {
                slimAdapterEx.notifyItemChanged(position);
            }

        });
    }

    @Override
    public void setView() {


    }

    public static class TagBean {
        public TagBean(String text) {
            this.text = text;
        }

        public TagBean(String text, boolean isCheck) {
            this.text = text;
            this.isCheck = isCheck;
        }

        public String text;
        public boolean isCheck = false;


    }
}
